from re import L
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib import auth
import os


g_dst_dir = "/home/liubenlong/openvpn"
g_dst_sh = "/home/liubenlong/openvpn/openvpn.sh"
g_clientinfo_file = "/home/liubenlong/openvpn/ovpn-data/openvpn-status.log"
g_client_file = "/home/liubenlong/openvpn/client.ovpn"

def login(request):
    if request.method == "GET":
        return render(request, "login.html")
    username = request.POST.get("username")
    password = request.POST.get("pwd")

    user_obj = auth.authenticate(username=username, password=password)
    print("login user is ", user_obj)

    if not user_obj:
        return redirect("/login/")
    else:
      rep = redirect("/index/")
      request.session['is_login'] = True
      request.session['user'] = username
      return rep
       
def index(request):
    return render(request, "index.html")

def logout(request):
    rep = redirect('/login/')
    request.session.flush()
    return rep # 点击注销后执行,删除cookie,不再保存用户状态，并弹到登录页面
   
def vpn_update(request):
    if request.method == "GET":
      return vpn_update_ack(request)

    port = request.POST.get("port")
    print('dst port is ', port)
    if port:
      print('update vpn port %s'%port)
      os.system('sed s/^PORT=.*/PORT=%s/ -i %s'%(port, g_dst_sh))
      os.system('%s stop'%g_dst_sh)
      os.system('%s run'%g_dst_sh)

    return vpn_update_ack(request)

def vpn_status(request):
  str='err'
  try:
    with open(g_clientinfo_file, 'r') as file_obj:
      str = file_obj.read()
  finally:
    pass
  # print(str)
  return HttpResponse(str, content_type='text/plain')

def vpn_client(request):
  str='err'
  try:
    with open(g_client_file, 'r') as file_obj:
      str = file_obj.read()
  finally:
    pass
  # print(str)
  return HttpResponse(str, content_type='text/plain')

def vpn_update_ack(request):
  return render(request, "vpn_update.html", {"last_port":get_vpn_port(g_dst_sh)})

def get_vpn_port(file):
  port='filerr'
  try:
    with open(file, 'r') as file_obj:
      lines = file_obj.readlines()
      for v in lines:
        sa = v.split('=')
        if len(sa) != 2:
          continue
        if sa[0] == 'PORT':
          port = sa[1]
          break
  finally:
    return port